export default {
  namespaced:true,
  state: () => ({
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart:uni.getStorageSync('cartNum')||[]
  }),
  mutations: {
    addCart(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      //如果没有则像购物车数组里添加
      if(findResult){
        findResult.goods_count++
      }else{
        state.cart.push(goods)
      }
      this.commit('m_cart/saveCartStorage')
    },
    saveCartStorage(state){
      uni.setStorageSync('cartNum',state.cart)
    },
    updateCart(state,goods){
      const findResult=state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult){
        findResult.goods_state = goods.goods_state
         this.commit('m_cart/saveCartStorage')
      }
    },
    updateCartCount(state,goods){
      const findResult=state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult){
        findResult.goods_count = goods.goods_count
         this.commit('m_cart/saveCartStorage')
      }
    },
    //购物车右滑删除
    swipeDel(state,goods_id){
             state.cart=state.cart.filter(x => x.goods_id !== goods_id)
             this.commit('m_cart/saveCartStorage')
             },
    //购物车全选状态更改
    updateAllState(state,newState){
      state.cart.forEach((x)=>x.goods_state=newState)
    }
  },
  
  getters: {
    total(state){
      let sum=0
     state.cart.forEach(item=>sum+=item.goods_count)
     return sum
    },
    //选中的数量
    checkedCount(state){
     return state.cart.filter(x=>x.goods_state).reduce((total,i)=>total+i.goods_count,0)
    },
    //选中的总价
    checkedPrice(state){
      return state.cart.filter(x=>x.goods_state).reduce((total,tp)=>total+tp.goods_count*tp.goods_price,0)
    }
  }
}
